package com.hmall.order.servie.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.OrderClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.ResultDTO;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.User;
import com.hmall.common.util.ThreadLocalUtil;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.OrderByPojo;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.servie.OrderService;
import com.hmall.order.vo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticMapper;

    @Override
    public Long createOrder(Order order) {
        //根据订单编号查询商品编号
        Item item = itemClient.getItemById(order.getItemId());
        Long userId = ThreadLocalUtil.getUserId();

        Long totalPrice = item.getPrice() * order.getNum();

        OrderByPojo orderByPojo = OrderByPojo.builder().totalFee(totalPrice)
                .paymentType(order.getPaymentType()).userId(userId).status(1).build();
        orderMapper.insert(orderByPojo);

        OrderDetail orderDetail = OrderDetail.builder().orderId(orderByPojo.getId()).itemId(item.getId())
                .num(order.getNum()).name(item.getName()).price(item.getPrice()).spec(item.getSpec()).image(item.getImage()).build();
        orderDetailMapper.insert(orderDetail);

        Address address = userClient.queryAddress(order.getAddressId());

        OrderLogistics orderLogistics = OrderLogistics.builder().orderId(orderByPojo.getId()).contact(address.getContact())
                .mobile(address.getMobile()).province(address.getProvince())
                .city(address.getCity()).town(address.getTown()).street(address.getStreet()).build();


        orderLogisticMapper.insert(orderLogistics);
        itemClient.modifyStock(item.getId(), -1);
        return orderByPojo.getId();
    }


    @Override
    public ResultDTO pay(Long orderId, String password) {
        //更加订单信息查询订单
        LambdaQueryWrapper<OrderByPojo> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(OrderByPojo::getId, orderId);
        OrderByPojo orderByPojo = orderMapper.selectOne(lambdaQuery);
        Boolean payResult = false;
        if (orderByPojo.getStatus() != null && orderByPojo.getStatus() == 1) {
            Long userId = ThreadLocalUtil.getUserId();
            User user = userClient.findUser(userId);
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
            if (user.getPassword().equals(md5DigestAsHex)) {

                Long totalFee = orderByPojo.getTotalFee();
                Long balance = userClient.queryBalance(userId);

                //余额不足
                if (balance < totalFee) {
                    orderClient.errorPage();
                    orderMapper.deleteById(orderId);
                    return new ResultDTO(false, null, null);
                }

                //支付订单
                payResult = userClient.UserPay(userId, totalFee);
            } else {
                orderClient.errorPage();
                orderMapper.deleteById(orderId);
            }
        }
        return new ResultDTO(payResult, null, null);
    }

    @Override
    public OrderByPojo getOrder(Long orderId) {
        OrderByPojo orderByPojo = orderMapper.selectById(orderId);
        return orderByPojo;
    }

    @Override
    public Integer getStatus(Long orderId) {
        OrderByPojo orderByPojo = orderMapper.selectById(orderId);
        return orderByPojo.getStatus();
    }
}
